<?php
declare(strict_types=1);
namespace Swb\Shop\Service;

use Hyperf\Database\Model\ModelNotFoundException;
use Hyperf\Utils\Context;
use Swb\Shop\Helper\ShopTrait;
use Swb\Shop\Model\TShop;
use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;
use Swb\Shop\Contract\ShopServiceInterface;

class RentShopService implements ShopServiceInterface
{
	use ShopTrait;
	public function getList(array $param=[])
	{
		$request        =ApplicationContext::getContainer()->get(RequestInterface::class);
		$keyword        =$search_param['keyword']??$request->input('keyword');
		$page           =$search_param['page']??$request->input('page', 1);
		$limit          =$search_param['limit']??$request->input('limit', 20);
		$area           =$search_param['area']??$request->input('area');
		$price          =$search_param['price']??$request->input('price', 0);
		$total_price    =$search_param['total_price']??$request->input('total_price', 0);
		$agent_id       =$search_param['agent_id']??$request->input('agent_id', 0);
		$business_id    =$search_param['business_id']??$request->input('business_id', 0);
		$except_hours_id=$search_param['except_hours_id']??$request->input('except_hours_id', 0);
		$count          =TShop::query()->where('del_flag', 1)->where('up_down_status', 1)->where('house_source', 1)->where('house_sale_rent', 1)->whereIn('house_status', [1, 2, 3, 5])->when($keyword, function (Builder $builder, $keyword){
			$builder->whereHas('building', function (Builder $query) use ($keyword){
			    $query->where(function ($query) use ($keyword){
                    $query->orWhere('t_building.building_name', 'like', "%$keyword%")
                        ->orWhere('t_shop.name', 'like', "%$keyword%");
                });
			});
		})->when($area, function ($builder, $area){
			$builder->whereHas('building', function (Builder $query) use ($area){
				$isArea=Db::table('sys_business_areas')->where('id', $area)->count();
				if ($isArea){
					$query->where('business_district_id', $area);
				}else{
					$area=Db::table('sys_business_areas')->where('area_id', $area)->pluck('id');
					$query->whereIn('business_district_id', $area);
				}
			});
		})->when($agent_id, function ($builder, $agent_id){
			return $builder->where('agent_id', $agent_id);
		})->when($total_price, function (Builder $builder, $total_price){
			$price=explode('-', $total_price);
			if (is_array($price)){
				$min_price=$price[0];
				$max_price=!isset($price[1]) ? 1000000000000 : $price[1];
				return $builder->whereRaw('(sale_price*floor_area) between ? and ?', [$min_price, $max_price]);
			}
		})->when($business_id, function ($builder, $business_id){
			return $builder->whereIn('id', $business_id);
		})->where(function ($builder) use ($price){
			if ($price){
				$price=explode('-', $price);
				if (is_array($price)){
					$min_price=$price[0];
					$max_price=!isset($price[1]) ? 1000000000000 : $price[1];
					return $builder->whereRaw('(rental_price*floor_area) between ? and ?', [$min_price, $max_price]);
				}
			}
		})->where(function ($builder) use ($request){
			$assignment_fee=$request->input('assignment_fee');
			if ($assignment_fee==1){
				return $builder->where('assignment_fee', '>', 0);
			}elseif ($assignment_fee==2){
				return $builder->whereNull('assignment_fee');
			}
		})->where(function ($builder) use ($request){
			$floorarea=$request->input('floorarea', 0);
			if ($floorarea){
				$floorarea=explode('-', $floorarea);
				if (is_array($floorarea)){
					$min_floor_area=$floorarea[0];
					$max_floor_area=$floorarea[1]??1000000000000;
					return $builder->whereBetween('floor_area', [$min_floor_area, $max_floor_area]);
				}
			}
		})->where(function ($builder) use ($request){
			$rent_free_period=$request->input('rent_free_period');
			if ($rent_free_period){
				//免租期 数字
				return $builder->where('rent_free_period', 200);
			}
		})->where(function ($builder) use ($request){
			$contract_term=$request->input('contract_term');
			if ($contract_term){
				//合同期 数字
				return $builder->where('contract_term', $contract_term);
				//
			}
		})->where(function ($builder) use ($request){
			$renovation_type=$request->input('renovation_type');
			if ($renovation_type){
				//装修类型 数字
				return $builder->where('renovation_type', $renovation_type);
				//
			}
		})->where(function ($builder) use ($request){
			$industries=$request->input('industries');
			if ($industries){
				//适合业态
				$label=explode(',', $industries);
				return $builder->whereHas('house_dict', function ($query) use ($label){
					$query->whereIn('dictionaries_name', $label);
				});
				//
			}
		})->where(function ($builder) use ($request){
			$label=$request->input('label');
			if ($label){
				//标签
				$label=explode(',', $label);
				return $builder->whereHas('house_dict', function ($query) use ($label){
					return $query->whereIn('dictionaries_name', $label);
				});
			}
		})->where(function (Builder $builder) use ($request){
			$infrastructure=$request->input('infrastructure');
			if ($infrastructure){
				//商业配套
				$label=explode(',', $infrastructure);
				return $builder->whereHas('house_dict', function ($query) use ($label){
					$query->whereIn('dictionaries_name', $label);

				});
				//
			}
		})->when($except_hours_id, function (Builder $builder, $except_hours_id){
			$builder->where('id', '<>', $except_hours_id);
		})->count();
		if ($count){
			$info       =TShop::query()->with(['building', 'house_dict'=>function ($query){
				$query->where('type', 3);
			}])->where('del_flag', 1)->where('up_down_status', 1)->whereIn('house_status', [1, 2, 3, 5])->where('house_source', 1)->where('house_sale_rent', 1)->when($keyword, function (Builder $builder, $keyword){
				$builder->whereHas('building', function (Builder $query) use ($keyword){
                    $query->where(function ($query) use ($keyword){
                        $query->orWhere('t_building.building_name', 'like', "%$keyword%")
                            ->orWhere('t_shop.name', 'like', "%$keyword%");
                    });
				});
			})->when($area, function ($builder, $area){
				$builder->whereHas('building', function (Builder $query) use ($area){
					$isArea=Db::table('sys_business_areas')->where('id', $area)->count();
					if ($isArea){
						$query->where('business_district_id', $area);
					}else{
						$area=Db::table('sys_business_areas')->where('area_id', $area)->pluck('id');
						$query->whereIn('business_district_id', $area);
					}
				});
			})->when($business_id, function ($builder, $business_id){
				return $builder->whereIn('id', $business_id);
			})->when($agent_id, function ($builder, $agent_id){
				return $builder->where('agent_id', $agent_id);
			})->where(function ($builder) use ($price){
				if ($price){
					$price=explode('-', $price);
					if (is_array($price)){
						$min_price=$price[0];
						$max_price=!isset($price[1]) ? 1000000000000 : $price[1];
						return $builder->whereRaw('(rental_price*floor_area) between ? and ?', [$min_price, $max_price]);
					}
				}
			})->where(function ($builder) use ($request){
				//rental_price  sale_price
				$floorarea=$request->input('floorarea', 0);
				if ($floorarea){
					$floorarea=explode('-', $floorarea);
					if (is_array($floorarea)){
						$min_floor_area=$floorarea[0];
						$max_floor_area=$floorarea[1]??1000000000000;
						return $builder->whereBetween('floor_area', [$min_floor_area, $max_floor_area]);
					}
				}
			})->where(function ($builder) use ($request){
				$rent_free_period=$request->input('rent_free_period');
				if ($rent_free_period){
					//免租期 数字
					return $builder->where('rent_free_period', 200);
				}
			})->where(function ($builder) use ($request){
				$contract_term=$request->input('contract_term');
				if ($contract_term){
					//合同期 数字
					return $builder->where('contract_term', $contract_term);
					//
				}
			})->where(function ($builder) use ($request){
				$renovation_type=$request->input('renovation_type');
				if ($renovation_type){
					//装修类型 数字
					return $builder->where('renovation_type', $renovation_type);
					//
				}
			})->where(function ($builder) use ($request){
				$industries=$request->input('industries');
				if ($industries){
					//适合业态
					$label=explode(',', $industries);
					return $builder->whereHas('house_dict', function ($query) use ($label){
						$query->whereIn('dictionaries_name', $label);

					});
					//
				}
			})->where(function ($builder) use ($request){
				$label=$request->input('label');
				if ($label){
					//标签
					$label=explode(',', $label);
					return $builder->whereHas('house_dict', function ($query) use ($label){
						return $query->whereIn('dictionaries_name', $label);
					});
				}
			})->where(function (Builder $builder) use ($request){
				$infrastructure=$request->input('infrastructure');
				if ($infrastructure){
					//商业配套
					$label=explode(',', $infrastructure);
					return $builder->whereHas('house_dict', function ($query) use ($label){
						$query->whereIn('dictionaries_name', $label);

					});

					//
				}
			})->where(function ($builder) use ($request){
				$assignment_fee=$request->input('assignment_fee');
				if ($assignment_fee==1){
					return $builder->where('assignment_fee', '>', 0);
				}elseif ($assignment_fee==2){
					return $builder->whereNull('assignment_fee');
				}
			})->when($total_price, function (Builder $builder, $total_price){
				$price=explode('-', $total_price);
				if (is_array($price)){
					$min_price=$price[0];
					$max_price=!isset($price[1]) ? 1000000000000 : $price[1];
					return $builder->whereRaw('(sale_price*floor_area) between ? and ?', [$min_price, $max_price]);
				}
			})->when($except_hours_id, function (Builder $builder, $except_hours_id){
				$builder->where('id', '<>', $except_hours_id);
			})->select('id', 'name', 'number', 'rental_price', 'sale_price', 'floor_area', 'useable_area', 'building_id', 'rental_price')->orderByRaw('house_status asc,deal_time desc')->forPage((int)$page, (int)$limit)->get();
			$collect_key=[];
			if ($business_id){
				$collect_key=array_flip((array)$business_id);
			}
			foreach ($info as &$item){

				$item['label']        =$item['house_dict'] ? bxy_search_array_value($item['house_dict'], 'type', 'dictionaries_name', 3) : [];
				$item['district_name']=$item['building']['area_name'] ?: '';
				$item['street_name']  =$item['building']['name'] ?: '';
				$logo                 =$this->get_logo($item['id']);
				$item['logo']         =$logo ?: config('swb_shop.default_image');
				if ($collect_key){
					$item['business_id']=$item['id'];
					$item['collect_id'] =$collect_key[$item['id']];
				}
			}
		}
		$response['lists']=$info??[];
		$response['limit']=(int)$limit;
		$response['page'] =(int)$page;
		$response['count']=$count;
		return $response;

	}

	public function getDetail(string $id)
	{
		try{
			$shop=TShop::query()->findOrFail($id);

			$build=$this->get_building($shop['building_id'], ['building_address', 'longitude', 'latitude', 'developers', 'booking_card_num', 'completion_date', 'count_total_shop']);
			$data=$this->get_rent_house($shop, $build, $id);
			$data['shop_look_pic']=config('swb_shop.default_shop_look_pic');
			$data['default_image']=config('swb_shop.default_image');
			return $data;
		}catch (ModelNotFoundException $e){
			return false;
		}
	}


}